
import 'package:bookshelf/entity/book_entity.dart';
import 'package:bookshelf/serial/send_helper.dart';
import 'package:bookshelf/util/toast_util.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:qr_flutter/qr_flutter.dart';
import '../main.dart';
import '../socket/send_helper.dart';
import '../widget/app_bar.dart';
import '../util/timer_manager.dart';

class Book extends StatefulWidget {
  const Book({Key? key}) : super(key: key);

  @override
  State<Book> createState() => _BookState();
}

class _BookState extends State<Book> {


  late BookEntity entity;

  RxBool showAnimation = false.obs;

  bool isLight = false;



  @override
  initState() {
    super.initState();

     entity = Get.arguments;

    WidgetsBinding.instance.addPostFrameCallback((_){
      timer.startCountDown(CountDownMode.action, (){
        timer.cancel();
        Get.until((route) => route.isFirst);
      });
    });
    _openLight();

  }

  _title(){
    return Container(
      width: double.infinity,
      margin: EdgeInsets.only(top: 10.h,left: 8.w,right: 8.w),
      child: Stack(
        alignment: AlignmentDirectional.centerStart,
        children: [
          InkWell(
            onTap: (){
              Get.back();
            },
            child: Image.asset("assets/images/back.png",width:50.w,fit: BoxFit.fitWidth,)
          ),
          Align(child: Text('书籍详情',style: TextStyle(color: Colors.white,fontSize: 12.sp,fontWeight: FontWeight.bold),)),
          Align(alignment:AlignmentDirectional.centerEnd, child: Obx(() => Text("${timer.actionTime.value}",style: TextStyle(color: Colors.white,fontSize: 8.sp),))),
        ],
      )
    );
  }


  _entity(){
    RxInt recommendCount = (entity.recommend_score??0).obs;
    return Container(
      width: double.infinity,
      margin: EdgeInsets.only(top:10.r,left: 8.r,right: 8.r),
      padding: EdgeInsets.only(top: 16.r,left: 16.r,right: 16.r),
      height: 170.h,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.all(Radius.circular(4.r)),
      ),
      child: Stack(
        children: [
          Positioned(child: Image.network('${entity.cover}',width: 80.w,height:110.h,fit: BoxFit.fill,
            errorBuilder: ( BuildContext context, Object error, StackTrace? stackTrace,){
              return  Image.asset('assets/images/default.png',width: 80.w,height:110.h,fit: BoxFit.fill);
            },),),
          Positioned(left:90.w,top:6.h,right: 10.w,
              child: SingleChildScrollView(
                scrollDirection: Axis.horizontal,
                child: Text('《${entity.title}》',maxLines:1,style: TextStyle(color: Colors.black,fontSize: 12.sp,fontWeight: FontWeight.bold),),
              )
          ),          Positioned(left:90.w,top:24.h,child: Text('${entity.author}',style: TextStyle(color: Colors.black,fontSize: 10.sp),),),
          Positioned(left:90.w,top:42.h,child: InkWell(
              onTap: (){
                resort.addByNo(entity.no);
                recommendCount.value = recommendCount.value +1;
                entity.recommend_score = recommendCount.value;
                if(!showAnimation.value){
                  showAnimation.value = true;
                  Future.delayed(const Duration(milliseconds: 300),(){
                    showAnimation.value = false;
                  });
                }
              },
              child: Image.asset("assets/images/like_click.png",width: 40.w,fit: BoxFit.fitWidth)
            )
          ),
          Positioned(left:100.w,top:12.h,child: Obx(() => InkWell(
            onTap: (){
              resort.addByNo(entity.no);
              recommendCount.value = recommendCount.value +1;
              entity.recommend_score = recommendCount.value;
              if(!showAnimation.value){
                showAnimation.value = true;
                Future.delayed(const Duration(milliseconds: 300),(){
                  showAnimation.value = false;
                });
              }
            },
            child: Visibility(visible:showAnimation.value,child: Image.asset("assets/images/star.gif",width: 40.w,fit: BoxFit.fitWidth)))),
          ),
          Positioned(left:125.w,top:38.h,child: Container(
            width: 10.w,
            height: 10.w,
            alignment: Alignment.center,
            decoration:  BoxDecoration(
                borderRadius: BorderRadius.all(Radius.circular(44.r)),
                color: const Color.fromRGBO(255, 0, 0, 1)
            ),
            child: Obx(() => Text('${recommendCount.value>999?'999+':recommendCount.value}',style: TextStyle(color: Colors.white, fontSize: 4.sp),)),
          )),
          Positioned(left:90.w,top:62.h,child: Text('位置：${_analyzePlace(entity.place)}',style: TextStyle(color: Colors.black,fontSize: 10.sp),),),
          Positioned(left:90.w,top:76.h,child: Text('索书号：${entity.search_no} ',style: TextStyle(color: Colors.black,fontSize: 10.sp),),),
          Positioned(left:90.w,top:90.h,child: Text('条码：${entity.no}',style: TextStyle(color: Colors.black,fontSize: 10.sp),),),
          Positioned(right:20.w,top:84.h,child: QrImageView(
            data: '${entity.title}\n位置：${_analyzePlace(entity.place)}\n索书号：${entity.search_no}\n条码：${entity.no}',
            version: QrVersions.auto,
            size: 50.w,
          ),),
          Positioned(right:10.w,top:135.h,child: Text('支付宝扫一扫查看图书存址',style: TextStyle(color: Colors.black,fontSize: 6.sp),),),

        ],
      )
    );
  }

  _analyzePlace(String? place){
    if(place == null || place.isEmpty){
      return '';
    }
    String room = place.substring(0,2);
    String column = place.substring(2,6);
    String side = place.substring(6,8);
    String knot = place.substring(8,10);
    String floor = place.substring(10,12);
    return '$room区$column列${side=='01'?'A面':'B面'}$knot节$floor层';
  }

  _position(){
    var floor = '';
    var isLeft = true;
    if(entity.place != null && entity.place != ''){
      floor = entity.place!.substring(10,12);
      isLeft = entity.place!.substring(6,8)=='01';
      if(settingEntity.exchange??false){
        isLeft = !isLeft;
      }
    }
    return Container(
        width: double.infinity,
        margin: EdgeInsets.only(top:8.r,left: 8.r,right: 8.r),
        padding: EdgeInsets.only(top: 26.r,left: 16.r,right: 16.r),
        height: 444.h,
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.all(Radius.circular(4.r)),
        ),
        child: (entity.place == null || entity.place == '' || entity.place!.substring(0,2) != settingEntity.roomNo || entity.place!.substring(2,6) != settingEntity.columnNo)?
          Column(
            children: [
              Image.asset("assets/images/lose.png",width: 280.w,fit: BoxFit.fitWidth,),
              Text((entity.place == null || entity.place == '')?'图书目前不在架':'图书不在本柜，请前往${entity.placeName}查看',style: TextStyle(color: Colors.blueAccent,fontSize: 12.sp,fontWeight: FontWeight.bold),),
            ],
          ):
          settingEntity.norms == '5层'?
          Column(
            children: [
              settingEntity.twoSided!?
                Text('请移步${entity.place!.substring(6,8)=='01'?'A面':'B面'}拿取图书',style: TextStyle(color: Colors.blueAccent,fontSize: 12.sp,fontWeight: FontWeight.bold),):
                Text('请根据指示灯拿取书籍',style: TextStyle(color: Colors.blueAccent,fontSize: 12.sp,fontWeight: FontWeight.bold),),
              SizedBox(height: 30.h,),
              Stack(
                children: [
                  Image.asset("assets/images/${settingEntity.twoSided!?'two':'single'}${isLeft?'_left':'_right'}.png",width: 320.w,fit: BoxFit.fitWidth,),
                  settingEntity.twoSided!?
                    Positioned(top:7.h,left:isLeft?66.w:200.w,child: Container(
                      height: 20.h,
                      width: 54.w,
                      alignment: Alignment.center,
                      child: Text('第${entity.place!.substring(8,10)}节',style: TextStyle(color: Colors.white,fontSize: 10.sp),),
                    ),):
                    Positioned(top:8.h,left:isLeft?72.w:193.w,child: Container(
                      height: 21.h,
                      width: 58.w,
                      alignment: Alignment.center,
                      child: Text('第${entity.place!.substring(8,10)}节',style: TextStyle(color: Colors.white,fontSize: 10.sp),),
                    ),),
                  settingEntity.twoSided!?
                  Positioned(top:(227-(int.parse(entity.place!.substring(10,12))-1)*47.5).h ,left:isLeft?9.w:142.3.w,child: Container(
                      height: 40.h,
                      width: 168.7.w,
                      alignment: Alignment.center,
                      decoration: const BoxDecoration(
                        color: Color.fromRGBO(62, 221, 216, 0.5),
                      ),
                      child: Text('书籍在此处',style: TextStyle(color: Colors.white,fontSize: 10.sp),),
                    ),):
                  Positioned(top:(246-(int.parse(entity.place!.substring(10,12))-1)*50.5).h ,left:isLeft?10.w:129.w,child: Container(
                      height: 42.h,
                      width: 180.w,
                      alignment: Alignment.center,
                      decoration: const BoxDecoration(
                        color: Color.fromRGBO(62, 221, 216, 0.5),
                      ),
                      child: Text('书籍在此处',style: TextStyle(color: Colors.white,fontSize: 10.sp),),
                    ),),
                  if(settingEntity.main??false)...[
                    settingEntity.twoSided!?
                    Positioned(top:20.h ,left:isLeft?240.w:30.w,
                      child: Image.asset("assets/images/light${isLeft?'_left':'_right'}.gif",width: 50.w,fit: BoxFit.fitWidth,),
                    ):
                    Positioned(top:24.h ,left:isLeft?235.w:35.w,
                      child: Image.asset("assets/images/light${isLeft?'_left':'_right'}.gif",width: 50.w,fit: BoxFit.fitWidth,),
                    )
                  ]
                ],
            ),
            SizedBox(height: 30.h,),
            if(settingEntity.main??false)...[
              InkWell(
                onTap: (){
                  _openLight();
                },
                child: Image.asset("assets/images/open_light.png",width: 100.w,fit: BoxFit.fitWidth,),
              )
            ]
          ],
        ):
          Column(
            children: [
              settingEntity.twoSided!?
              Text('请移步${entity.place!.substring(6,8)=='01'?'A面':'B面'}拿取图书',style: TextStyle(color: Colors.blueAccent,fontSize: 12.sp,fontWeight: FontWeight.bold),):
              Text('请根据指示灯拿取书籍',style: TextStyle(color: Colors.blueAccent,fontSize: 12.sp,fontWeight: FontWeight.bold),),
              SizedBox(height: 30.h,),
              Stack(
                children: [
                  Image.asset("assets/images/${settingEntity.twoSided!?'two':'single'}${isLeft?'_left_6':'_right_6'}.png",width: 320.w,fit: BoxFit.fitWidth,),
                  settingEntity.twoSided!?
                  Positioned(top:7.h,left:isLeft?66.w:200.w,child: Container(
                    height: 20.h,
                    width: 54.w,
                    alignment: Alignment.center,
                    child: Text('第${entity.place!.substring(8,10)}节',style: TextStyle(color: Colors.white,fontSize: 10.sp),),
                  ),):
                  Positioned(top:8.h,left:isLeft?72.w:193.w,child: Container(
                    height: 21.h,
                    width: 58.w,
                    alignment: Alignment.center,
                    child: Text('第${entity.place!.substring(8,10)}节',style: TextStyle(color: Colors.white,fontSize: 10.sp),),
                  ),),
                  settingEntity.twoSided!?
                  Positioned(top:floor == '01'?232.h:floor == '02'?195.h:floor == '03'?155.h:floor == '04'?115.h:floor == '05'?75.h:34.h ,left:isLeft?9.w:142.3.w,child: Container(
                    height: 34.h,
                    width: 168.7.w,
                    alignment: Alignment.center,
                    decoration: const BoxDecoration(
                      color: Color.fromRGBO(62, 221, 216, 0.5),
                    ),
                    child: Text('书籍在此处',style: TextStyle(color: Colors.white,fontSize: 10.sp),),
                  ),):
                  Positioned(top:floor == '01'?250.h:floor == '02'?211.h:floor == '03'?168.h:floor == '04'?125.h:floor == '05'?81.h:38.h ,left:isLeft?10.w:129.w,child: Container(
                    height: 37.h,
                    width: 181.w,
                    alignment: Alignment.center,
                    decoration: const BoxDecoration(
                      color: Color.fromRGBO(62, 221, 216, 0.5),
                    ),
                    child: Text('书籍在此处',style: TextStyle(color: Colors.white,fontSize: 10.sp),),
                  ),),
                  if(settingEntity.main??false)...[
                    settingEntity.twoSided!?
                    Positioned(top:20.h ,left:isLeft?240.w:30.w,
                      child: Image.asset("assets/images/light${isLeft?'_left':'_right'}.gif",width: 50.w,fit: BoxFit.fitWidth,),
                    ):
                    Positioned(top:24.h ,left:isLeft?235.w:35.w,
                      child: Image.asset("assets/images/light${isLeft?'_left':'_right'}.gif",width: 50.w,fit: BoxFit.fitWidth,),
                    )
                  ]
                ],
              ),
              SizedBox(height: 30.h,),
              if(settingEntity.main??false)...[
                InkWell(
                  onTap: (){
                    _openLight();
                  },
                  child: Image.asset("assets/images/open_light.png",width: 100.w,fit: BoxFit.fitWidth,),
                )
              ]

            ],
          )
    );
  }

  _openLight() async {
    if(isLight){
      toastWarn('灯已点亮');
      return;
    }
    var places = settingEntity.place;
    if(places != null){
      var place = places.firstWhereOrNull((element) => element.place == entity.place);
      if(place != null){
        if(settingEntity.main??false){
          var data = await openLight(place.ant!);
          hfSerialPortHelper.sendData(data);
          toastWarn('灯已闪烁');
        }

      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () => FocusScope.of(context).requestFocus(FocusNode()),
      child: Scaffold(
        resizeToAvoidBottomInset: false,
        body: Container(
          width: double.infinity,
          height: double.infinity,
          decoration: const BoxDecoration(
            image: DecorationImage(
              fit: BoxFit.fill,
              image: AssetImage(
                "assets/images/bg.png",
              ),
            ),
          ),
          child: Column(
            children: [
              appBar(),
              _title(),
              _entity(),
              _position()
            ],
          ),
        ),
      ),
    );
  }
}

